package com.byzk.p2p.admin.fuiou.util;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientHelper{
    
    public static String doHttp(String urlStr,String charSet,Object parameters, String timeOut) throws Exception{
    	String responseString="";
    	PostMethod xmlpostMethod;
 	    int statusCode = 0;
 	    HttpClient httpclient = new HttpClient();
 	    httpclient.setConnectionTimeout(new Integer(timeOut).intValue());
 	    xmlpostMethod = new PostMethod(urlStr);
 	    httpclient.getParams().setParameter(
 	    		HttpMethodParams.HTTP_CONTENT_CHARSET, charSet);
        try{
        	//组合请求参数
        	List<NameValuePair> list=new ArrayList<NameValuePair>();
			Method[] ms=parameters.getClass().getMethods();
			for(int i=0;i<ms.length;i++){
				Method m=ms[i];
				String name=m.getName();
				if(name.startsWith("get")){
					String param=name.substring(3,name.length());
					param=param.substring(0,1).toLowerCase()+param.substring(1,param.length());
					if(param.equals("class")){
						continue;
					}
					Object value="";
					try {
						value = m.invoke(parameters, null);
						NameValuePair nvp=new NameValuePair(param,value.toString());
						list.add(nvp);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						throw e;
					}
				}
			}
			NameValuePair[] nvps=new NameValuePair[list.size()];
			xmlpostMethod.setRequestBody(list.toArray(nvps)); 
        	statusCode = httpclient.executeMethod(xmlpostMethod);
	    	responseString = xmlpostMethod.getResponseBodyAsString();
            if(statusCode<HttpURLConnection.HTTP_OK || statusCode>=HttpURLConnection.HTTP_MULT_CHOICE){
                System.err.println("失败返回码[" + statusCode + "]");
                throw new Exception("请求接口失败，失败码[ "+ statusCode +" ]");
            }
        }catch(IOException e){
            e.printStackTrace();
            System.err.println(e.toString());
            throw e;
        }finally {
    	  if(xmlpostMethod != null) { //不要忘记释放，尽量通过该方法实现
    		  xmlpostMethod.releaseConnection();
    		  }
        }
        return responseString;
    }

	/**
	 * 
	* <p>Description:get请求方式 </p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2016年11月7日下午12:31:48
	 */
	public void doGet(String url, String charset) {
		HttpClient httpClient = new HttpClient();
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
		// 创建get实例
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		getMethod.setFollowRedirects(true);
		String response = "";
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("请求出错: " + getMethod.getStatusLine());
			}
			Header[] headers = getMethod.getResponseHeaders();
			for (Header h : headers)
				System.out.println(h.getName() + "------------ " + h.getValue());
			byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
			response = new String(responseBody, charset);
			Header header = getMethod.getResponseHeader("location");
			System.out.println("----------response:" + header);
		} catch (HttpException e) {
			System.out.println(e.getMessage());
		} catch (IOException e1) {
			System.out.println(e1.getMessage());
		} finally {
			getMethod.releaseConnection();
		}
	}
    
}
